package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/app/model/commonmodel"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"math"
)

var MsgTemplateService = &MsgTemplate{}

type MsgTemplate struct {
}

func (s *MsgTemplate) Add(r *model.MsgTemplateMgrServicesAddReq) bool {

	InsertId := dao.BackgroundMsgTemplate.Add(r)
	dao.UserRelData.Add(model.USER_REL_DATA_TYPE_MsgTemplate_MAIL, InsertId, r.MailUserList)
	dao.UserRelData.Add(model.USER_REL_DATA_TYPE_MsgTemplate_PHONE, InsertId, r.PhoneUserList)

	return true
}

func (s *MsgTemplate) Edit(r *model.MsgTemplateMgrServicesEditReq) bool {

	dao.BackgroundMsgTemplate.Edit(r.Id, r)

	templateType := []int{model.USER_REL_DATA_TYPE_MsgTemplate_MAIL, model.USER_REL_DATA_TYPE_MsgTemplate_PHONE}
	_, err := dao.UserRelData.Where(dao.UserRelData.Columns.Type+" IN (?)", templateType).
		Where(dao.UserRelData.Columns.Id, r.Id).Delete()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}

	res := dao.UserRelData.Add(model.USER_REL_DATA_TYPE_MsgTemplate_MAIL, int64(r.Id), r.MailUserList)
	if res != true {
		defErr.Panic(define.DataOptFail)
	}

	res = dao.UserRelData.Add(model.USER_REL_DATA_TYPE_MsgTemplate_PHONE, int64(r.Id), r.PhoneUserList)
	if res != true {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *MsgTemplate) Del(r *model.MsgTemplateMgrServicesDelReq) bool {

	_, err := dao.BackgroundMsgTemplate.Where("id IN (?)", r.Ids).Delete()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	_, err = dao.UserRelData.Where("id IN (?)", r.Ids).Delete()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *MsgTemplate) List(r *model.MsgTemplateMgrServiceListReq) (pageInfo commonmodel.PageInfo, data []*model.BackgroundMsgTemplate) {

	nums, err := dao.BackgroundMsgTemplate.Count()
	defErr.IfPanic(err, define.DataOptFail)

	pageInfo = commonmodel.PageInfo{
		Total: nums,
		Cur:   r.Page,
		PNum:  int(math.Ceil(float64(nums) / float64(r.PageSize))),
	}

	data, err = dao.BackgroundMsgTemplate.Page(r.Page, r.PageSize).Order(dao.BackgroundMsgTemplate.Columns.ChangeTime + " desc").All()
	defErr.IfPanic(err, define.DataOptFail)

	if r.Page > pageInfo.PNum {
		if r.Page == 1 {
			defErr.Panic(define.RecordNodFound)
		} else {
			defErr.Panic(define.PageOverPageLimit)
		}
	}

	return pageInfo, data

}
